﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NangLuongTieuDiemBUS.BUS;
using NangLuongTieuDiemBUS;
using NangLuongTieuDiemDTO.DTO;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Menu;
using DevExpress.XtraEditors.Repository;
using System.IO;
using NangLuongTieuDiemGUI.NangLuongTieuDiemForms;


namespace NangLuongTieuDiemGUI.NangLuongTieuDiemUserControl
{

    public partial class ucDanhSachThietBiDien : UserControl
    {

        #region "[khai báo biến toàn cục]"
        /// <summary>
        /// Người tạo: Mr.chau
        /// Ngày tạo: 30/05/2013
        /// Mô tả: Biến lưu đường dẫn đến thư mục cần tạo file excel
        /// </summary>
        public static string m_strPathExportExcel = string.Empty;
        #endregion

        #region "[khởi tạo mặc định]"
        public ucDanhSachThietBiDien()
        {
            InitializeComponent();
        }
        #endregion

        //khai bao
        bool LaSo ;
        // string ChuoiTimKiem; 
        #region "[Hàm kiểm tra dữ liệu của ô tim kiem la chuoi hay so]"
        public bool KiemTraLaSo(string pValue)
        {
            foreach (Char c in pValue)
            {
                if (!Char.IsDigit(c))
                   return false;
            }
           return true;
        }
        #endregion

        #region "[Thực hiện chức năng tìm kiếm khi bam vào nút Tìm Kiếm]"
        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            try 
            {
                if (KiemTraLaSo(txtThongtin.Text) == true)
                    LaSo = true;
                else
                    LaSo = false;
                TimKiem_ThietBiDien();
            }

            catch (Exception ex)
            {
                InSert_LoiHeThong("btnTimKiem_Click", ex);
            }
        }
        #endregion
       
        #region "[Hàm Tìm Kiếm]"// Doan Phu An - 1241302
        void TimKiem_ThietBiDien()
        {
            int SoThietBiDienTimDuoc;
            if (txtThongtin.Text == "" || txtThongtin.Text == "Nhập từ khóa cần tìm")
            {
                MessageBox.Show("Phải nhập từ khóa cần tìm ", "Thông Báo");
                return;
            }
            try
            {
                List<ThietBiDienDTO> list = new List<ThietBiDienDTO>();
                list = NangLuongTieuDiem_Management.TimKiemThietBiDien(txtThongtin.Text).Where(p => p.Xoa == false).ToList();
                SoThietBiDienTimDuoc = list.Count();
                if (list.Count > 0)
                {
                    List<ThietBiDienDTO> listAll = new List<ThietBiDienDTO>();
                    listAll = NangLuongTieuDiem_Management.ThietBiDien_GetAll().Where(p => p.Xoa == false).ToList();
                    foreach (ThietBiDienDTO tbdDTO in listAll)
                    {
                        if(LaSo == true)
                        {
                            if (tbdDTO.CongSuat.ToString() != txtThongtin.Text
                                && tbdDTO.CongSuatHaoHut.ToString() != txtThongtin.Text
                               && tbdDTO.HeSoDeBa.ToString() != txtThongtin.Text
                               && !tbdDTO.TenThietBiDien.ToLower().Contains(txtThongtin.Text) 
                               && !tbdDTO.GhiChu.ToLower().Contains(txtThongtin.Text))
                            {
                                list.Add(tbdDTO);
                            }

                        }
                        else
                        {
                            if ( !tbdDTO.TenThietBiDien.ToLower().Contains(txtThongtin.Text) && !tbdDTO.GhiChu.ToLower().Contains(txtThongtin.Text))
                            {
                                list.Add(tbdDTO);
                            }
                        }
                    }
                    dgvHienThi.DataSource = list;
                    gridView1.GroupPanelText = string.Format("Tìm được: {0}/{1} Thiết Bị Điện ",SoThietBiDienTimDuoc,listAll.Count());
                    btnxuatrafileexcel.Enabled = true;
                }
                else
                {
                    dgvHienThi.DataSource = null;
                    gridView1.GroupPanelText = string.Format("Không tìm thấy '{0}' trong thiết bị điện",txtThongtin.Text);
                    btnxuatrafileexcel.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("TimKiem_ThietBiDien", ex);
            }

        }
        #endregion
       
        #region "[bấm enter vào khung textbox]"
        /// <summary>
        /// MrChau
        /// bấm enter vào khung textbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtThongtin_KeyUp(object sender, KeyEventArgs e)
        {
            try 
            {
                if (e.KeyCode == Keys.Enter)
                { 
                    btnTimKiem_Click(null,null);
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("txtThongtin_KeyUp", ex);
            }
        }
        #endregion

        #region "[xu ly khi click vào khung textbox]"
        private void txtThongtin_Click(object sender, EventArgs e)
        {
            if (txtThongtin.Text == "Nhập từ khóa cần tìm")
                txtThongtin.Text = "";
        }
        #endregion

        #region "[đánh số thứ tự cho gird view]"// Doan Phu An - 1241302
        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.Column == clSoThuTu)
            {
                e.DisplayText = Convert.ToString(e.RowHandle + 1);
            }
            //to mau nhung dong tim duoc
            if (LaSo == true)
            {
                string CongSuat = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "CongSuat"));
                if (CongSuat == txtThongtin.Text)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "CongSuat")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                    }
                }

                string CongSuatHaoHut = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "CongSuatHaoHut"));
                if (CongSuatHaoHut == txtThongtin.Text)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "CongSuatHaoHut")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                    }
                }

                string HeSoDeBa = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "HeSoDeBa"));
                if (HeSoDeBa == txtThongtin.Text)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "HeSoDeBa")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                    }
                }
                string TenThietBiDien = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "TenThietBiDien")).ToLower();
                if (TenThietBiDien.Contains(txtThongtin.Text) == true)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "TenThietBiDien")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                    }

                }
                //doi voi ghi chu
                string GhiChu = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "GhiChu")).ToLower();
                if (GhiChu.Contains(txtThongtin.Text) == true)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "GhiChu")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                    }
                }
               
            }
            else
            {
                //doi voi ten thiet bi dien 
                string TenThietBiDien = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "TenThietBiDien")).ToLower();
                if (TenThietBiDien.Contains(txtThongtin.Text) == true)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "TenThietBiDien")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font,FontStyle.Bold);
                    }
                  
                }
                //doi voi ghi chu
                string GhiChu = Convert.ToString(gridView1.GetRowCellValue(e.RowHandle, "GhiChu")).ToLower();
                if (GhiChu.Contains(txtThongtin.Text) == true)
                {
                    e.Appearance.BackColor = Color.Pink;
                    if (e.Column.FieldName == "GhiChu")
                    {
                        e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                    }
                }
            }

            }
        #endregion

        #region "[bấm enter vào khung textbox]"// Doan Phu An - 1241302
        private void txtThongtin_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                try
                {
                    if (KiemTraLaSo(txtThongtin.Text) == true)
                        LaSo = true;
                    else
                        LaSo = false;
                    TimKiem_ThietBiDien();
                }
                catch (Exception ex)
                {
                    InSert_LoiHeThong("txtThongtin_KeyPress", ex);
                }
            }
        }
        #endregion

        #region "[hàm xử lý update 1 dong du lieu]"// Doan Phu An - 1241302
        void OnUpdateRowClick(object sender, EventArgs e)
        {
            try
            {
                DXMenuItem item = sender as DXMenuItem;
                RowInfo info = item.Tag as RowInfo;
                ThietBiDienDTO tbdDto = new ThietBiDienDTO();
                tbdDto.ID = Convert.ToInt32(gridView1.GetRowCellValue(info.RowHandle, "ID").ToString());
                tbdDto.TenThietBiDien = gridView1.GetRowCellValue(info.RowHandle, "TenThietBiDien").ToString();
                tbdDto.CongSuat = Convert.ToDouble(gridView1.GetRowCellValue(info.RowHandle, "CongSuat"));
                tbdDto.CongSuatHaoHut = Convert.ToDouble(gridView1.GetRowCellValue(info.RowHandle, "CongSuatHaoHut"));
                tbdDto.HeSoDeBa = Convert.ToInt32(gridView1.GetRowCellValue(info.RowHandle, "HeSoDeBa"));
                tbdDto.GhiChu = gridView1.GetRowCellValue(info.RowHandle, "GhiChu").ToString();
                NangLuongTieuDiem_Management.ThietBiDien_Update(tbdDto);
                MessageBox.Show("Dữ liệu đã được lưu lại ...", "Thông Báo");
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("OnUpdateRowClick", ex);
            }
        }
        #endregion

        #region "[hàm xử lý khi clicl phải vào 1 dong tren luoi]"// Doan Phu An - 1241302
        private void gridView1_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.MenuType == GridMenuType.Row)
                {
                    int rowHandle = e.HitInfo.RowHandle;
                    e.Menu.Items.Clear();
                    DXMenuItem menuItem;
                    menuItem = new DXMenuItem("Lưu lại", new EventHandler(OnUpdateRowClick));
                    menuItem.Tag = new RowInfo(view, rowHandle);
                    e.Menu.Items.Add(menuItem);
                    menuItem = new DXMenuItem("Xóa", new EventHandler(OnDeleteRowClick));
                    menuItem.Tag = new RowInfo(view, rowHandle);
                    e.Menu.Items.Add(menuItem);
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView1_PopupMenuShowing", ex);
            }
        }
        #endregion

        #region "[hàm Xoa 1 dong hien tai]"// Doan Phu An - 1241302
        /// <summary>
        /// Xoa 1 dong duoc chon
        /// </summary>
        void OnDeleteRowClick(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Bạn có muốn xóa dòng vừa chọn ?", "Thông Báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DXMenuItem item = sender as DXMenuItem;
                    RowInfo info = item.Tag as RowInfo;
                    NangLuongTieuDiem_Management.ThietBiDien_Delete(Convert.ToInt32(gridView1.GetRowCellValue(info.RowHandle, "ID")));
                    info.View.DeleteRow(info.RowHandle);
                }


            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("OnDeleteRowClick", ex);
            }

        }
        #endregion

        #region "[Thong Tin cua dong hien tai]"// Doan Phu An - 1241302
        class RowInfo
        {
            public RowInfo(GridView view, int rowHandle)
            {
                this.RowHandle = rowHandle;
                this.View = view;
            }
            public GridView View;
            public int RowHandle;
        }
        #endregion

        #region "[hàm xử lý khi clicl phải vào 1 dong tren luoi]"// Doan Phu An - 1241302
        private void gridView1_PopupMenuShowing_1(object sender, PopupMenuShowingEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.MenuType == GridMenuType.Row)
                {
                    int rowHandle = e.HitInfo.RowHandle;
                    e.Menu.Items.Clear();
                    DXMenuItem menuItem;
                    menuItem = new DXMenuItem("Lưu lại", new EventHandler(OnUpdateRowClick));
                    menuItem.Tag = new RowInfo(view, rowHandle);
                    e.Menu.Items.Add(menuItem);
                    menuItem = new DXMenuItem("Xóa", new EventHandler(OnDeleteRowClick));
                    menuItem.Tag = new RowInfo(view, rowHandle);
                    e.Menu.Items.Add(menuItem);
                }
            }
            catch (Exception ex)
            {
                InSert_LoiHeThong("gridView1_PopupMenuShowing_1", ex);
            }
        }
        #endregion
        
        #region "[Load]"
        private void ucDanhSachThietBiDien_Load(object sender, EventArgs e)
        {
            try 
            {
                btnTimKiem.Enabled = false;
                btnxuatrafileexcel.Enabled = false;
                List<ThietBiDienDTO> listAll = new List<ThietBiDienDTO>();
                listAll = NangLuongTieuDiem_Management.ThietBiDien_GetAll().Where(p => p.Xoa == false).ToList();
                dgvHienThi.DataSource = listAll;
                gridView1.GroupPanelText = string.Format("Có tất cả: {0} thiết bị điện", listAll.Count());
            }
            catch { }
        }
        #endregion

        #region "[xuất ra file excel]"
        private void xuatrafileexcel_Click(object sender, EventArgs e)
        {
            try {
                frmLuuDuongDan frm = new frmLuuDuongDan();
                frm.ShowDialog();

                if (m_strPathExportExcel != string.Empty)
                {
                    gridView1.ExportToXls(m_strPathExportExcel);
                }
                
            }
            catch { }
        }
        #endregion

        #region "[Hàm xu ly nut tim kiem]"
        private void txtThongtin_EditValueChanged(object sender, EventArgs e)
        {
            if (txtThongtin.Text != "")
            {
                btnTimKiem.Enabled = true;
            }
            else
            {
                btnTimKiem.Enabled = false;
            }
        }
        #endregion

        #region "[Hàm insert lỗi hệ thống]"
        public void InSert_LoiHeThong(string TenHam, Exception ex)
        {
            LoiHeThongDTO lhtDto = new LoiHeThongDTO();
            lhtDto.TenLoi = ex.Message.ToString();
            lhtDto.NgayTao = DateTime.Now;
            lhtDto.TenHamBiLoi ="ucDanhSachThietBiDien_" + TenHam;
            lhtDto.SuaLoi = false;
            lhtDto.GhiChu = "";
            NangLuongTieuDiem_Management.LoiHeThong_Insert(lhtDto);
            MessageBox.Show(lhtDto.TenLoi);
        }
        #endregion

     

    }
}
